#include "mmTest_Stain.h"

_mmTest_Stain mmTest_Stain;

bool _mmTest_Stain::_Init() {



	Flag_Inited = TRUE;
	return TRUE;
}

bool _mmTest_Stain::RunTest(uuByteFig& ByteFig) {
	Mat FigMat = xx::ByteFigToMat(ByteFig);
	if (FigMat.rows == 0 || FigMat.cols == 0 || FigMat.channels() == 0) {
		return false;
	}

	cvtColor(FigMat, FigMat, CV_BGR2GRAY);
	GaussianBlur(FigMat, FigMat, Size(5, 5), 1.0);


	
	Mat mSobelX, mSobelY;
	Sobel(FigMat, mSobelX, CV_16S, 1, 0, 7);
	Sobel(FigMat, mSobelY, CV_16S, 0, 1, 7);
	convertScaleAbs(mSobelX, mSobelX);
	convertScaleAbs(mSobelY, mSobelY);

	Mat mEdge;
	addWeighted(mSobelX, 1, mSobelY, 1, 0, mEdge);

	Mat mThresh;
	threshold(mEdge, mThresh, 0, 255, THRESH_BINARY | THRESH_OTSU);

	Mat kernel1 = getStructuringElement(MORPH_RECT, Size(11, 11));

	Mat mMorph;
	morphologyEx(mThresh, mMorph, MORPH_ERODE, kernel1);

	Mat kernel2 = getStructuringElement(MORPH_RECT, Size(5, 5));
	morphologyEx(mMorph, mMorph, MORPH_DILATE, kernel2);

	std::vector<std::vector<Point>> contours;
	findContours(mMorph, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);

	for (int i = 0; i < (int)contours.size(); i++)
	{
		double area = contourArea(contours[i]);
		if (area > 200)
		{
			drawContours(FigMat, contours, i, Scalar(0, 0, 255));

		}
	}
	
	ByteFig.FigC = 1;
	memcpy(ByteFig.BmpSource, FigMat.data, ByteFig.FigMem());

	Flag_TestResult = (contours.size() == 0) ? TRUE : false;

	return TRUE;
}